<?php
namespace Cyfy\Modules\ListBoxes;

use \Cyfy\Modules\Users\Current;
/**
 * Listboxes
 * @author Dandelion <dandelion8888@gmail.com>
 */
class Module extends \Cyfy\Module
{
    const DIR = "listbox/";
    
	/* Blocks*/
    static function blocks($lid = 0)
    {
        // a box is selected 
        if($lid != 0)
		{
            // when moving with templates
            if(\Cyfy\Blocks :: $forcedShow){
                return "<p>LISTBOX #{$lid}</p>";
            }
            
            
            // smart box?
            if($lid == -1){
                return self :: smartBox();
            }
            
            // ordinary
            return self :: getBox($lid);
        }

        // no box selected
        $result = \dibi :: query("SELECT [lid], [name] FROM [:cyfy:ListBoxes-boxes]");
        if(count($result) == 0){
            return array();
        }

        // some found
        $listboxes = array(-1 => self :: t(900));
        foreach($result as $l)
        {
            $listboxes[$l["lid"]] = $l["name"]; 
        }
        return $listboxes;
    }
    
    static function ajax($name)
    {
        switch($name)
        {
            case "loadData":
                return self :: ajaxLoadData();
            case "saveWeights":
                return self :: ajaxSaveWeights();
            case "storeActive":
                return self :: ajaxStoreActive();
            case "deleteItem":
                return self :: ajaxDeleteItem($_POST["liid"]);                
            case "deleteBox":
                return self :: ajaxDeleteBox($_POST["lid"]);     
                
            case "listOfBoxes":
                return self :: ajaxListOfBoxes();
            case "listOfItems":
                return self :: ajaxListOfItems();
        }
    }
 
 
	static private function ajaxStoreActive()
	{
		$_SESSION["listboxes"][$_POST["lid"]] = $_POST["active"];
	}
 
	static private function ajaxLoadData()
	{
		$result = \dibi :: query("SELECT [liid], [image], [content] FROM [:cyfy:ListBoxes-items] WHERE lid = %i ", $_POST["lid"], " AND weight = %i", $_POST["active"]);
        
		if(count($result) == 0)
        {
			return "";
		}
		self :: ajaxStoreActive();
		return (array) $result->fetch();	
	}
	
	static private function ajaxSaveWeights()
	{
        if(!Current :: hasPermission("ListBoxes", "administration"))
        {
            \Cyfy\Cyfy :: noPermission();
            return false;
        }    
            
            
		if(!is_array($_POST["weight"]))
		{
            return false;
        }

        foreach($_POST["weight"] as $liid => $weight)
        {
            \dibi :: query("UPDATE [:cyfy:ListBoxes-items] SET weight = %i" , $weight , " WHERE liid = %i", $liid);
        }			
        \Cyfy\Message :: set(self :: t(100));
	}
	
	
    
    
    
    static private function ajaxDeleteItem($liid)
	{
        if(!Current :: hasPermission("ListBoxes", "administration"))
        {
            \Cyfy\Cyfy :: noPermission();
            return false;
        }    
        
		// get the item
		$result =\dibi :: query("SELECT [liid], [lid], [image] FROM [:cyfy:ListBoxes-items] WHERE [liid] = %i", $liid);
        
        // if not found
		if(count($result) == 0){
            return false;
        }
			
        $li = $result -> fetch();
			
        	
        // delete the image
        \Cyfy\Cyfy ::  delete(\Cyfy\Cyfy ::  $filesDir . self :: DIR . $li["lid"] . "/" . $li["image"]);
        
        // delete the item
        \dibi :: query("DELETE FROM [:cyfy:ListBoxes-items] WHERE [liid] = %i", $_POST["liid"]);
			
        // UPDATE WEIGTHS
		$weight = 0;
		$result = \dibi :: query("SELECT [liid] FROM `[:cyfy:ListBoxes-items] WHERE [lid] = '{$li["lid"]}' ORDER BY [weight] ASC");
        foreach($result as $li){
            $weight++;
            \dibi :: query("UPDATE [:cyfy:ListBoxes-items] SET [weight] = $weight WHERE [liid] = '{$li["liid"]}'");
		}
        return true;
	}
    
    
    static private function ajaxDeleteBox($lid)
	{
        if(!Current :: hasPermission("ListBoxes", "administration"))
        {
            \Cyfy\Cyfy :: noPermission();
            return false;
        }    
        
		// delete the images
        \Cyfy\Cyfy ::  delete(\Cyfy\Cyfy ::  $filesDir . self :: DIR . $lid);
        
        // delete the items
        \dibi :: query("DELETE FROM [:cyfy:ListBoxes-items] WHERE [lid] = %i", $lid);
		
        // delete the box
        \dibi :: query("DELETE FROM [:cyfy:ListBoxes-boxes] WHERE [lid] = %i", $lid);
        
        \Cyfy\Message :: set(self :: t(850));
        return true;
	}
  
  

    
    /**
	 * List of Listboxes
	 */
	static function ajaxListOfBoxes()
    {
        if(!Current :: hasPermission("ListBoxes", "administration"))
        {
            \Cyfy\Cyfy :: noPermission();
            return false;
        }    
        
		$result = \dibi :: query("SELECT [lid], [code], [name] FROM [:cyfy:ListBoxes-boxes]");
		
		if(count($result) == 0)
        {
			return \Cyfy\Message :: get(self :: t(200), \Cyfy\Message :: WARNING);
		}
        
        // list of listboxes
        $table = new \Cyfy\Modules\Objects\Table();
        $table -> header(array(self :: t(210), self :: t(220), self :: t(730)));
        
        foreach($result as $l)
        {
            $edit = "<input type=\"submit\" value=\"E\" onclick=\"Cyfy.redirectTo('administration/ListBoxes/listOf/{$l["lid"]}'); return false;\" /> ";
            $edit .= "<input type=\"submit\" value=\"D\" onclick=\"if(confirm('" . self :: t(840) . "')){ Cyfy.ajax('ListBoxes', 'deleteBox', '', 'lid={$l["lid"]}'); Cyfy.ajax('ListBoxes', 'listOfBoxes', '#listOfListBoxes'); } return false;\" />";
            $table -> row(array($l["name"], $l["code"], $edit));
		}
		return $table->show();
	}
    
    /**
	  * List of Listboxes items
	  */
	static function ajaxListOfItems($lid)
    {
        if(!Current :: hasPermission("ListBoxes", "administration"))
        {
            \Cyfy\Cyfy :: noPermission();
            return false;
        }    
        
		$result = \dibi :: query("SELECT * FROM [:cyfy:ListBoxes-items] WHERE [lid] = %i ORDER BY [weight] ASC", $lid);
		
        if(count($result) == 0)
        {
			return \Cyfy\Message :: get(self :: t(510), \Cyfy\Message :: WARNING);
		}
        
        $output = "";
        // list of listboxes items

        
        $table = new \Cyfy\Modules\Objects\Table();
        $table -> header(array(self :: t(710), self :: t(720), self :: t(730)));
        $table -> classes(array('liid', 'name', 'edit'));
        foreach($result as $l)
        {
            $edit = "<input type=\"submit\" value=\"E\" onclick=\"ListboxAdmin.editItem({$l["lid"]}, {$l["liid"]}); return false;\" /> ";
            $edit .= "<input type=\"submit\" value=\"D\" onclick=\"if(confirm('" . self :: t(740) . "')){ ListboxAdmin.deleteItem({$l["liid"]}); } return false;\" />";
            $table -> row(array($l["liid"], $l["name"], $edit));
		}
		return $table->show();
	}
    
    
      
  
  
	/**
	  * Administration
	  */	
    static function administration($name = "")
    {
        switch($name)
        {
            case "listOf":
                return self :: administrationMain();
                
            case "":
                return array(
                    "listOf" => array("name" => self :: t(10), "description" => self :: t(20), "permission" => "administration"),
                );
		}
    }
     

     
	static private function administrationMain()
	{
        if(!Current :: hasPermission("ListBoxes", "administration"))
        {
            \Cyfy\Cyfy :: noPermission();
            return false;
        }    
        
        // if selected box
        if(\Cyfy\Cyfy ::  arg(3))
        {
            // if selected item
            if(\Cyfy\Cyfy ::  arg(4))
            {
                return self :: itemDetail(\Cyfy\Cyfy ::  arg(3), \Cyfy\Cyfy ::  arg(4));
            }
            return self :: detail(\Cyfy\Cyfy ::  arg(3));
        }
        
        
        // if not - list
		$output .= "<div id=\"listOfListBoxes\">" . self :: ajaxListOfBoxes() . "</div>\n";

        // new box
		$form = new Forms\NewBox();
		
        $c = new \Cyfy\Modules\Objects\Collapsible();
        $c -> setData(self :: t(310), $form -> show(), true);
		$output .= $c -> show();
        
		return $output;
	}
	

	
	/**
	  * ListBox detail
	  */
	static private function detail($lid)
    {
        if(!Current :: hasPermission("ListBoxes", "administration"))
        {
            \Cyfy\Cyfy :: noPermission();
            return false;
        }    
        
		$result = \dibi :: query("SELECT * FROM [:cyfy:ListBoxes-boxes] WHERE [lid] = %s", $lid);
		if(count($result) == 0){
            return false;
        }
			
        // load Javascript
        \Cyfy\Modules\jquery\Plugins :: load("jqueryUI");
        \Cyfy\Cyfy ::  javaScript(\Cyfy\Cyfy ::  getSourcePath("Cyfy/Modules/ListBoxes/admin.js"), "file");
    
        $l = $result ->fetch();
        
        $output = "<h2>" . self :: t(401, array($l["name"])) . "</h2>\n";
        $output .= "<div id=\"listOfListBoxesItems\">" . self :: ajaxListOfItems($l["lid"]) . "</div>\n";
        $output .= "<br />\n";
        
        $output .= "<div class=\"form-buttons\" id=\"ListBoxesSaveWeight\"><input type=\"submit\" value=\"" . self :: t(410) . "\" /></div>";
			
		$output .= "<br />\n";
		
        //        new item
		$form = new Forms\NewItem();
        $form -> setTemp("lid", $l["lid"]);
        $form -> setTemp("code", $l["code"]);
		$c = new \Cyfy\Modules\Objects\Collapsible();
        $c -> setData(self :: t(420), $form -> show(), true);
		$output .= $c -> show();

        // Edit box
		$form = new Forms\EditBox();
        $form -> setTemp("lid", $l["lid"]);
        $form -> setData((array) $l);
		$c = new \Cyfy\Modules\Objects\Collapsible();
        $c -> setData(self :: t(430), $form -> show(), true);
		$output .= $c -> show();
        
        return $output;
	}
	
    
    static private function itemDetail($lid, $liid)
    {
        if(!Current :: hasPermission("ListBoxes", "administration"))
        {
            \Cyfy\Cyfy :: noPermission();
            return false;
        }    
        
        
        $result = \dibi :: query("SELECT * FROM [:cyfy:ListBoxes-items] WHERE [lid] = %i ", $lid , " AND [liid] = %i", $liid);
		if(count($result) == 0){
            return false;
        }
        
        $form = new Forms\EditItem();
        $form -> setTemp("liid", $liid);
        $form -> setTemp("lid", $lid);
        $form -> setData($result -> fetch());
        
        $output = "<h2>" . self :: t(610) . "</h2>";
        $output .= $form -> show();

        return $output;
    }
	
    
    
    
    
	
	/**
	  *	get new weight
	  */
	static function getNewWeight($lid)
    {
		$result = \dibi :: query("SELECT [weight] FROM [:cyfy:ListBoxes-items] WHERE lid = %i ORDER BY [weight] DESC LIMIT 1", $lid);
		if(count($result) == 0){
			return 1;
		}
        
        $l = $result -> fetch();
        return $l['weight'] + 1;
	}
    
    
    /**
     * Smart box returns a box according to first part of the URL
     */
    static function smartBox()
    {
        $code = \Cyfy\Cyfy :: arg(0);
        // try the code
        $result = \dibi :: query("SELECT [lid] FROM [:cyfy:ListBoxes-boxes] WHERE [code] = %s", $code);
        if(count($result) == 0){
            // if not found - index
            $result = \dibi :: query("SELECT [lid] FROM [:cyfy:ListBoxes-boxes] WHERE [code] = %s", 'index');
            if(count($result) == 0){
                // if not found, return false
                return false;
            }
        }
        
        //return the box
        return self :: getBox($result -> fetchSingle());    
    }
    
    
    static function getBox($lid)
    {
        // get data for current listbox
        $result = \dibi :: query("SELECT [lid], [code] FROM [:cyfy:ListBoxes-boxes] WHERE [lid] = %i", $lid);
			
		// if not found
		if(count($result) == 0){
            return false;
        }
        
        // get the box
        $l = $result -> fetch();
				
        // load all items
        $result = \dibi :: query("SELECT [liid], [image], [content] FROM [:cyfy:ListBoxes-items] WHERE [lid] = %i ORDER BY [weight] ASC", $lid);

        // if no items found
		if(count($result) == 0){
            return false;
        }

        // the path, where images are stored
        $path = \Cyfy\Cyfy ::  $filesDir . self :: DIR . $l["lid"] . "/";
        
        // preload all images
        $jsPreloadData = "";
        foreach($result as $i)
        {
            $jsPreloadData .= "lbPreloadImg{$i["liid"]} = new Image(); lbPreloadImg{$i["liid"]}.src = '" . \Cyfy\Cyfy :: getSourcePath($path . $i["image"]) . "'; ";
        }
				
        // get the previous position
        $position = ($_SESSION["listboxes"][$lid]) ? $_SESSION["listboxes"][$lid] : 1;
        
        // seek to the result
        if($result -> seek($position - 1) == false){
            $position = 1;
        }				
				
        // some avascripts
        \Cyfy\Cyfy ::  javascript(\Cyfy\Cyfy :: getSourcePath("Cyfy/Modules/ListBoxes/listbox.js"), "file", "header");
        \Cyfy\Cyfy ::  javascript("Listbox.lid = $lid; Listbox.count = " . count($result) . "; Listbox.path = '{$path}'; Listbox.active = $position; " . $jsPreloadData, "inline", "footer");
        
        // data of the first
        $image = "";
        $content = "";
        
        $liids = array();
        $first = true;
				
        $li = $result -> fetch();
        $image = \Cyfy\Cyfy ::  getSourcePath($path . $li["image"]);
        $content = $li["content"];
        $first = false;

        // pager
        $pager = "";
        for($i = 1; $i <= count($result); $i++)
        {
			$pager .= "<li class=\"num\"" . (($i == $position) ? " id=\"listbox-active\"" : "") . "><a href=\"#{$i}\">{$i}</a></li>\n";
        }
		
        // print
				
		$output = <<<OUTPUT

<div id="listbox" class="listbox">
    <div class="listbox-image-bg"></div>
    <img class="listbox-image" src="$image" alt="" />				
    <div class="listbox-content">
        $content
    </div>
    
    <div class="listbox-pager">
        <div class="listbox-left"></div>
        <div class="listbox-center">	
            <ul>
                <li class="listbox-prev"><a href="#prev">&lt;</a></li>
                $pager
                <li class="listbox-next"><a href="#next">&gt;</a></li>
            </ul>
        </div>
        <div class="listbox-right"></div>
    </div>
</div>
OUTPUT;
		return $output;
    }
}